package cn.edu.usst.cs.goldfish.booking.meetingroom.interceptor;

import cn.edu.usst.cs.goldfish.booking.meetingroom.web.SessionKeys;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import static cn.edu.usst.cs.goldfish.booking.meetingroom.web.SessionKeys.*;

/**
 * 拦截未认证用户登录除认证以外其他所有后端请求
 */
@Slf4j
@Component
public class AuthInterceptor extends ApiInterceptor {

    public AuthInterceptor() {
        super();
    }


    @Override
    public boolean preHandle(
            @lombok.NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull Object handler
    ) {

        request.getParameterMap().forEach(
                (key, value) -> {
                    log.info(" * key: {}, value: {}", key, value);
                }
        );
        int active = 10;
        LocalDateTime now = LocalDateTime.now();
        response.setContentType("application/json;charset=UTF-8");
        HttpSession session = request.getSession(false);


        if (session == null) {
            processResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "未登录");
            return false;
        }


        Object obj = session.getAttribute(LOGIN_TIME);
        if (!(obj instanceof LocalDateTime time)) {
            processResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "会话状态异常，请重新登录");
            return false;
        }

        if (time.plusMinutes(active).isBefore(now)) {
            processResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "会话已过期，请重新登录");
            return false;
        }
        session.setMaxInactiveInterval(60 * active);
        session.setAttribute(LOGIN_TIME, now);

        return true;
    }


}